/**
 * 基础三角形渲染示例
 * 演示WebGPU批量渲染框架的使用
 */

import '../src/js/webgpu-optimized-impl.js';

async function main() {
    console.log('Starting WebGPU batch rendering triangle demo...');
    
    // 获取canvas元素
    const canvas = document.getElementById('webgpu-canvas') || createCanvas();
    const context = canvas.getContext('webgpu');
    
    // 获取优化的WebGPU设备 - 开发者无需知道这是优化版本
    const adapter = await navigator.gpu.requestAdapter();
    const device = await adapter.requestDevice();
    
    console.log('WebGPU device acquired');
    
    // 配置canvas上下文
    const canvasFormat = navigator.gpu.getPreferredCanvasFormat();
    context.configure({
        device: device,
        format: canvasFormat,
        alphaMode: 'premultiplied'
    });
    
    // 顶点着色器 - 标准WGSL代码
    const vertexShaderCode = `
        @vertex
        fn main(@builtin(vertex_index) vertexIndex: u32) -> @builtin(position) vec4<f32> {
            var pos = array<vec2<f32>, 3>(
                vec2<f32>(-0.5, -0.5),
                vec2<f32>( 0.5, -0.5),
                vec2<f32>( 0.0,  0.5)
            );
            return vec4<f32>(pos[vertexIndex], 0.0, 1.0);
        }
    `;
    
    // 片元着色器
    const fragmentShaderCode = `
        @fragment
        fn main() -> @location(0) vec4<f32> {
            return vec4<f32>(1.0, 0.0, 0.0, 1.0); // 红色
        }
    `;
    
    // 创建着色器模块 - 标准WebGPU API调用
    const vertexShader = device.createShaderModule({
        code: vertexShaderCode
    });
    
    const fragmentShader = device.createShaderModule({
        code: fragmentShaderCode
    });
    
    console.log('Shaders created');
    
    // 创建渲染管线 - 标准WebGPU API调用
    const renderPipeline = device.createRenderPipeline({
        vertex: {
            module: vertexShader,
            entryPoint: 'main'
        },
        fragment: {
            module: fragmentShader,
            entryPoint: 'main',
            targets: [{
                format: canvasFormat
            }]
        },
        primitive: {
            topology: 'triangle-list'
        },
        layout: 'auto'
    });
    
    console.log('Render pipeline created');
    
    // 渲染循环
    function render() {
        // 获取当前纹理视图
        const textureView = context.getCurrentTexture().createView();
        
        // 创建命令编码器 - 标准WebGPU API
        const encoder = device.createCommandEncoder();
        
        // 开始渲染通道 - 标准WebGPU API
        const renderPass = encoder.beginRenderPass({
            colorAttachments: [{
                view: textureView,
                clearValue: { r: 0.0, g: 0.0, b: 0.0, a: 1.0 },
                loadOp: 'clear',
                storeOp: 'store'
            }]
        });
        
        // 设置渲染管线 - 标准WebGPU API
        renderPass.setPipeline(renderPipeline);
        
        // 绘制三角形 - 标准WebGPU API
        renderPass.draw(3); // 3个顶点
        
        // 结束渲染通道
        renderPass.end();
        
        // 完成命令编码并提交 - 标准WebGPU API
        const commandBuffer = encoder.finish();
        device.queue.submit([commandBuffer]);
        
        console.log('Frame rendered');
        
        // 请求下一帧
        requestAnimationFrame(render);
    }
    
    // 开始渲染
    render();
}

function createCanvas() {
    const canvas = document.createElement('canvas');
    canvas.id = 'webgpu-canvas';
    canvas.width = 800;
    canvas.height = 600;
    canvas.style.border = '1px solid black';
    document.body.appendChild(canvas);
    return canvas;
}

// 错误处理
window.addEventListener('error', (event) => {
    console.error('Error:', event.error);
});

// 页面加载完成后启动
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', main);
} else {
    main();
}

export { main };